package org.drl.tvkit.widget;

import org.drl.tvkit.KitApplication;
import org.drl.tvkit.R;
import org.drl.tvkit.util.HttpHelper;
import org.drl.tvkit.util.UrlFormatUtil;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PaintFlagsDrawFilter;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.nostra13.universalimageloader.utils.L;

/**
 * 海报组件
 * 
 * @author Darry Ring
 * 
 */
@SuppressLint("DrawAllocation")
public class MovieView extends ImageView {
	private ShadowView mShadowView;
	private Animation scaleSmallAnimation;
	private Animation scaleBigAnimation;
	private int cornerRadiusPixels=10;
	private String mImageFile;
	private ImageLoader mImageLoader;
	private String TAG = "MovieView";
	private int mDrawGYCount = 2;
	private int mDrawGYPading=0;
	private int mChildCount = 2;
	/**
	 * 光效果绘图调试,在无法正常显示光效果的时候，开启即可
	 */
	private boolean debugDraw = Boolean.FALSE;
	public MovieView(Context context) {
		super(context);
		init(null, 0);
	}

	public MovieView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(attrs, 0);
	}

	public MovieView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		init(attrs, defStyle);
	}
	Drawable mGDrawable;
	private void init(AttributeSet attrs, int defStyle) {
		if(attrs!=null){
			 TypedArray a = getContext().obtainStyledAttributes(attrs,
		                R.styleable.MoviceView, defStyle, 0);
			 mDrawGYCount = a.getInt(R.styleable.MoviceView_DrawGCount, 2);
			 mDrawGYPading = a.getInt(R.styleable.MoviceView_DrawGPading, 65);
			 mChildCount = a.getInt(R.styleable.MoviceView_ChildCount, 2);
			 a.recycle();
			 
		}else{
			mDrawGYCount = 2;
			mDrawGYPading = 65;
		}
		mGDrawable = getResources().getDrawable(R.drawable.ic_movice_focued);
		setFocusable(Boolean.TRUE);
		setFocusableInTouchMode(Boolean.TRUE);
		if (KitApplication.getInstance() != null) {
			mImageLoader = KitApplication.getInstance().getImageLoader();
		}
		buildImageShadowOptionis();
		final ShadowManager _sm = ShadowManager.getInstance(getContext().getApplicationContext());
		if(_sm!=null){
			_sm.removeShadowCacheFile(this);
		}
	}

	protected void findByShadowView() {
		ViewParent _p = getParent();
		if(_p!=null && MovieLayout.class.isInstance(_p)){
			MovieLayout _group = (MovieLayout) _p;
			if(_group.getChildCount()==mChildCount){
				for(int i=0;i<_group.getChildCount();i++){
					View _view = _group.getChildAt(i);
					if (_view != null && _view.getClass().getSimpleName().equals(ShadowView.class.getSimpleName())) {
						setShadowView((ShadowView) _view);
						return;
					}
				}
			}
		}
	}
	@Override
	protected void onAttachedToWindow() {
		super.onAttachedToWindow();
		findByShadowView();
		//
		 if (mGDrawable != null) {
			 mGDrawable.setVisible(getVisibility() == VISIBLE, false);
	     }
	}
	@Override
	protected void onDetachedFromWindow() {
		super.onDetachedFromWindow();
		if (mGDrawable != null) {
			 mGDrawable.setVisible(false, false);
	     }
	}

	@Override
	protected void onFocusChanged(boolean gainFocus, int direction,
			Rect previouslyFocusedRect) {
		super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
		if (mShadowView != null) {
			// 带倒影的组件
			if(gainFocus){
			   bringToFront();
			}
			View rootView = (View) getParent();
			rootView.setSelected(gainFocus);
		} else {
			// 不带倒影组件
			if (gainFocus) {
				View rootView = (View) getParent();
				if(rootView!=null&&ViewGroup.class.isInstance(rootView)){
					ViewGroup _vg = (ViewGroup) rootView;
					if(_vg.getChildCount()==1){
						bringToFront();
						rootView.setSelected(gainFocus);
					}else{
						bringToFront();
						zoomOut(this);
					}
				}else{
					bringToFront();
					zoomOut(this);
				}
			} else {
				zoomIn(this);
			}
		}
		postInvalidate();
	}

	@Override
	protected void onDraw(Canvas canvas) {
		if (canvas != null) {
			canvas.setDrawFilter(new PaintFlagsDrawFilter(0,
					Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG));
		}
		
		if(mGDrawable!=null && isFocused()){
			if(getDrawable()!=null){
				Rect _rect = getDrawable().getBounds();
				mGDrawable.setBounds(
						_rect.left - mDrawGYPading, 
						_rect.top - mDrawGYPading,
						_rect.right + mDrawGYPading,
						_rect.bottom + mDrawGYPading);
				//
				if(debugDraw){
					ColorDrawable _cd = new ColorDrawable(Color.RED);
					_cd.setBounds(mGDrawable.getBounds());
					_cd.draw(canvas);
				}
				//
				View pv = (View) getParent();
				pv.postInvalidate();
				for(int i=0;i<mDrawGYCount;i++){
					mGDrawable.draw(canvas);
				}
			}
			
		}
		super.onDraw(canvas);
		//==============DEBUG=========================================
		if(debugDraw){
			if(mGDrawable!=null && isFocused()){
				if(getDrawable()!=null){
					Rect _rect = getDrawable().getBounds();
					mGDrawable.setBounds(
							_rect.left - mDrawGYPading, 
							_rect.top - mDrawGYPading,
							_rect.right + mDrawGYPading,
							_rect.bottom + mDrawGYPading);
					View pv = (View) getParent();
					pv.postInvalidate();
					for(int i=0;i<mDrawGYCount;i++){
						mGDrawable.draw(canvas);
					}
				}
				
			}
		}
		//==============DEBUG=========================================
		
	}
	@Override
	protected void onAnimationEnd() {
		super.onAnimationEnd();
		invalidate();
	}
	

	public ShadowView getShadowView() {
		return mShadowView;
	}

	private DisplayImageOptions mShadowOptions = null;

	private void buildImageShadowOptionis() {
		if (mShadowOptions == null) {
			mShadowOptions = new DisplayImageOptions.Builder()
					// .resetViewBeforeLoading(true)
					.cacheOnDisk(false).cacheInMemory(true)
					.resetViewBeforeLoading(true)
					.bitmapConfig(Bitmap.Config.ARGB_8888).build();
		}
	}

	public void setShadowView(ShadowView mShadowView) {
		this.mShadowView = mShadowView;
	}

	private void zoomIn(View _view) {
		if (scaleSmallAnimation == null) {
			scaleSmallAnimation = AnimationUtils.loadAnimation(getContext(),
					R.anim.anim_scale_small);
		}
		_view.startAnimation(scaleSmallAnimation);
	}

	private void zoomOut(View _view) {
		if (scaleBigAnimation == null) {
			scaleBigAnimation = AnimationUtils.loadAnimation(getContext(),
					R.anim.anim_scale_big);
		}
		_view.startAnimation(scaleBigAnimation);
	}

	public void loadShadowAsyn(String file) {
		if (mImageLoader != null && mShadowView != null) {

			mImageLoader.displayImage(UrlFormatUtil.formatUrlFile(file),
					mShadowView, mShadowOptions, new ImageLoadingListener() {
						@Override
						public void onLoadingStarted(String arg0, View arg1) {
						}

						@Override
						public void onLoadingFailed(String arg0, View arg1,
								FailReason arg2) {
						}

						@Override
						public void onLoadingComplete(String arg0, View arg1,
								Bitmap arg2) {
							if (isFocused()) {
								if (mShadowView != null) {
									// 带倒影的组件
									View rootView = (View) getParent();
									rootView.setSelected(isFocused());
								}
							}
						}

						@Override
						public void onLoadingCancelled(String arg0, View arg1) {
						}
					});
		}
	}

	public int getCornerRadiusPixels() {
		return cornerRadiusPixels;
	}

	public void setCornerRadiusPixels(int cornerRadiusPixels) {
		this.cornerRadiusPixels = cornerRadiusPixels;
	}
	private DisplayImageOptions options = null;

	private void buildImageOptionis() {
		if (options == null) {
			options = new DisplayImageOptions.Builder()
					// .resetViewBeforeLoading(true)
					.cacheOnDisk(false).cacheInMemory(true)
					.displayer(new RoundedBitmapDisplayer(10))
					.bitmapConfig(Bitmap.Config.ARGB_8888).build();
		}
	}
	public String getImageFile() {
		return mImageFile;
	}

	public void setImageFile(String mImageFile) {
		L.i(TAG, "-setImageFile-->" + mImageFile);
		this.mImageFile = mImageFile;
		loadImageAysn(mImageFile);
	}
	
	public String getShadowFileName(){
		StringBuilder _builder = new StringBuilder();
		_builder.append(getId());
		_builder.append("_");
		if(mImageFile!=null){
			_builder.append(HttpHelper.toEncryptedName(mImageFile));
		}
		_builder.append(getWidth());
		_builder.append("x");
		_builder.append(getHeight());
		_builder.append(".png");
		return _builder.toString();
	}
	
	public void reloadShadow()
	{
		setDrawingCacheEnabled(Boolean.TRUE);
		if (mShadowView != null) {
			ShadowManager _sm = ShadowManager.getInstance(getContext());
			if (_sm != null) {
				_sm.loadShadowAsyn(MovieView.this,getShadowView());
			}
		}
	}
	int count = 0;

	public void loadImageAysn(final String file) {
		if (mImageLoader != null) {
			buildImageOptionis();
			mImageLoader.displayImage(file, this, options,
					new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							super.onLoadingComplete(imageUri, view, loadedImage);
							setDrawingCacheEnabled(Boolean.TRUE);
							if (mShadowView != null) {
								ShadowManager _sm = ShadowManager.getInstance(getContext().getApplicationContext());
								if(_sm!=null){
									_sm.loadShadowAsyn(MovieView.this, getShadowView());
								}
							}
							count = 0;
						}

						@Override
						public void onLoadingStarted(String imageUri, View view) {
							super.onLoadingStarted(imageUri, view);
							count++;
						}

						@Override
						public void onLoadingFailed(String imageUri, View view,
								FailReason failReason) {
							super.onLoadingFailed(imageUri, view, failReason);
							if (count < 4) {
								loadImageAysn(file);
							}else{
								if (mShadowView != null) {
									ShadowManager _sm = ShadowManager.getInstance(getContext().getApplicationContext());
									if(_sm!=null){
										_sm.loadShadowAsyn(MovieView.this, getShadowView());
									}
								}
							}
						}
					});
		}
	}

	public int getDrawGYCount() {
		return mDrawGYCount;
	}

	public void setDrawGYCount(int mDrawGYCount) {
		this.mDrawGYCount = mDrawGYCount;
		postInvalidate();
	}

	public boolean isDebugDraw() {
		return debugDraw;
	}

	public void setDebugDraw(boolean debugDraw) {
		this.debugDraw = debugDraw;
		postInvalidate();
	}

	public int getChildCount() {
		return mChildCount;
	}

	public void setChildCount(int mChildCount) {
		this.mChildCount = mChildCount;
		postInvalidate();
	}

}
